package wx

import (
	"context"
	"fmt"
	"gitee.com/go_love/db"
	"gitee.com/go_love/wxapi"
	"gitee.com/xmcommon/mlog"
	"github.com/mongodb/mongo-go-driver/bson"
	"github.com/mongodb/mongo-go-driver/bson/primitive"
	"github.com/mongodb/mongo-go-driver/mongo/options"
)

type SendBody struct {
	AccessToken string                 `json:"access_token"`
	Touser      string                 `json:"touser"`
	TemplateId  string                 `json:"template_id"`
	Page        string                 `json:"page"`
	FormId      string                 `json:"form_id"`
	Data        map[string]interface{} `json:"data"`
}

func PushMessageWX(uuid, content, pageType string) (err error) {
	var tempMap map[string]interface{}

	collection := db.MongoDB.Collection("user_formid")
	opts := options.FindOne()
	opts.SetSort(bson.M{"create_at": 1})
	filter := bson.M{"uuid": uuid}
	opts.SetProjection(bson.M{"_id": 1, "form_id": 1, "open_id": 1})
	err = collection.FindOne(context.Background(), filter, opts).Decode(&tempMap) //获取唯一标识id
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	tempId, ok := tempMap["_id"].(primitive.ObjectID)
	if !ok {
		err = fmt.Errorf("mongo get _id failed")
		mlog.Log.Error(err.Error())
		return
	}
	openId, ok := tempMap["open_id"].(string)
	if !ok {
		err = fmt.Errorf("mongo get open_id failed")
		mlog.Log.Error(err.Error())
		return
	}
	formId, ok := tempMap["form_id"].(string)
	if !ok {
		err = fmt.Errorf("mongo get form_id failed")
		mlog.Log.Error(err.Error())
		return
	}
	collection.DeleteOne(context.Background(), bson.M{"_id": tempId})

	accessToken := GetWXAccessToken()
	jumpPage := "pages/common/index/main"
	if pageType != "" {
		jumpPage += "?type=" + pageType
	}
	expires, err := wxapi.PushMsg(accessToken, openId, formId, content, jumpPage)
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	} else if expires {
		err = fmt.Errorf("accessToken expires")
		mlog.Log.Error(err.Error())
		return
	}

	return
}
